<?php

class Database {

	static protected $dbhLink = NULL;
	protected $dbh;

	function dbh() {
		return $this->dbh;
	}
	
	function Database() {
		if( self::$dbhLink === NULL ) {
			require('lib/config/database.php');
			extract( $database );
			self::$dbhLink = new PDO(
				"mysql:dbname=$dbname;host=$host",
				$username, 
				$password
			);
			self::$dbhLink->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
		}
		$this->dbh = self::$dbhLink;
	}
	
	function execute( $sql, array $params = null ) {
		$s = $this->dbh->prepare( $sql ); 
		if( $s === false ) throw new Exception($this->dbh->errorInfo, $this->dbh->errorCode);
		if( $s->execute( $params ) ) return $s->rowCount();
		else throw new Exception($this->dbh->errorInfo, $this->dbh->errorCode);
	}
	
	function getAll( $sql, array $params = null) {
		$s = $this->dbh->prepare( $sql );
		if( $s->execute( $params ) ) return $s->fetchAll( PDO::FETCH_ASSOC );
		else throw new Exception($this->dbh->errorInfo, $this->dbh->errorCode);
	}
	
	function executeMultiple($sql, array $paramset) {
		$s = $this->dbh->prepare( $sql );
		if( $s === false ) throw new Exception($this->dbh->errorInfo, $this->dbh->errorCode);
		else {
			$count = 0;
			$this->startTrans();
			foreach( $paramset as $params ) {
				$response = $s->execute( $params );
				if( $response === false ) {
					$this->rollBack();
					throw new Exception($this->dbh->errorInfo, $this->dbh->errorCode);
				}
				$count += $s->rowCount();
			}
			$this->commit();
			return $count;
		}
	}

	function lastInsertId() {
		return $this->dbh->lastInsertId();
	}
	
	function startTrans() {
		$this->dbh->beginTransaction();
	}
	
	function rollBack() {
		$this->dbh->rollBack();
	}
	
	function commit() {
		$this->dbh->commit();
	}
	
}